﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using TTQT.TTQT_Code;
using TTQT.TTQT_Code.Info;

namespace TTQT.Administration
{
    /// <summary>
    /// Summary description for Login.
    /// </summary>
    public partial class Login : System.Web.UI.Page
    {

        protected void Page_Load(object sender, System.EventArgs e)
        {
            //Response.Redirect("http://10.53.3.49/qlac/");
            //lblLoginStatus.Visible = false;
            //string str = txtUserName.ClientID;
            //Page.RegisterClientScriptBlock("connecError", "<script language =\"javascript\">\n alert(\""+str+"Không kết nối được CSDL!\");\n </script>");
            //Page.RegisterClientScriptBlock("Focus", "<script language =\"javascript\">\ndocument.getElementById('"+ txtUserName.ClientID+"').focus();</script>");
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {

        }
        #endregion

        protected void btnLogin_Click(object sender, System.EventArgs e)
        {
            int pageId = TTQTCommon.ToInt32(Request.QueryString["PageId"], 0);
            int userId =
                DataAccessObject.instance().checkLogin(this.txtUserName.Text.Trim(),
                TTQTCommon.MD5Encrypt(this.txtPassword.Text.Trim()));
            if (userId == -100)
            {
                //Page.RegisterClientScriptBlock("connecError", "<script language =\"javascript\">\n alert(\"Không kết nối được CSDL!\");\n </script>");
                Response.Redirect("../LostConnection.html");
                return;
            }
            if(userId==-101)
            {
                MyWebUtils.MyWebUtil.alert(this.Page,"User này đang bị khóa. Bạn vui lòng liên hệ admin chi nhánh để mở khóa");
                return;
            }
            if (userId > 0)
            {
                /***** Kiem tra chay dau ngay  *****/
                try
                {
                    int result = -1;
                    SqlConnection conn = new SqlConnection(TTQTCommon.DBConnectionString);
                    SqlCommand comm = new SqlCommand("Flag_ChayDauNgay_Check", conn);
                    comm.CommandType = CommandType.StoredProcedure;
                    try
                    {
                        conn.Open();
                        result = Convert.ToInt32(comm.ExecuteScalar());
                    }
                    catch (Exception ex)
                    {
                        // Write log method here
                    }
                    if (result <= 0) // Chưa chạy đầu ngày thì chạy đầu ngày
                    {
                        comm.CommandText = "_XuLiDauNgay";
                        comm.Parameters.Clear();
                        comm.Parameters.AddWithValue("@Ngay",
                                                     TTQTCommon.convertDateString(DateTime.Now.ToString("dd/MM/yyyy")));
                        comm.ExecuteScalar();
                        conn.Close();
                        comm.Dispose();
                    }
                }
                catch (Exception exxxx) { }
                /***** Ket thuc Kiem tra chay dau ngay  *****/

                Session["group_names"] = DataAccessObject.instance().getAllGroupNamesByUserId(userId);
                //TTQTCommon.LoginUser(this.txtUserName.Text.Trim(),this.chkRememberPwd.Checked);
                // Add Information to Session
                //				if(Session["UserId"]==null)
                //					Session.Add("UserId",userId.ToString());
                //				else
                UserInfo userInfo = DataAccessObject.instance().getUser(userId);
                Session["UserInfo"] = userInfo;
                DataAccessObject.instance().updateLastLogin(userInfo.userName);
                Session["Brn_Code"] = userInfo.Brn_Code;
                Session["UserId"] = userId.ToString();
                //				if(Session["UserName"] ==null)
                //					Session.Add("UserName",this.txtUserName.Text.Trim());
                //				else
                Session["UserName"] = this.txtUserName.Text.Trim().ToLower();
                Session["UserFullName"] = userInfo.fullName + " ( " + userInfo.userName + " )";
                Session["IsSuperAdmin"] = userInfo.isSuperAdmin;
                Session["SIBSID"] = userInfo.SIBSID;
                Session["GroupId"] = userInfo.groupId;
                Session["TenChiNhanh"] = userInfo.TenChiNhanh;
                // Ghi log
                LogInfo logInfo = new LogInfo();
                logInfo.Brn_Code = userInfo.Brn_Code;
                logInfo.Content = "Đăng nhập";
                logInfo.Ip = Request.UserHostAddress;
                logInfo.UserName = txtUserName.Text;
                logInfo.Type = TTQTCommon.log_DangNhap;
                DataAccessObject.instance().addLog(logInfo);
                Response.Redirect("../Default.aspx?PageId="+pageId);
                // add User information into Context
            }
            else
            {
                lblLoginStatus.Text = "Sai tên hoặc mật khẩu!";
                return;
            }
        }
    }
}